package com.example.forumsystem.demos.web.controller;

import com.example.forumsystem.demos.web.common.Constans;
import com.example.forumsystem.demos.web.common.ResultCode;
import com.example.forumsystem.demos.web.model.Result;
import com.example.forumsystem.demos.web.model.UserInfo;
import com.example.forumsystem.demos.web.service.IUserService;
import com.example.forumsystem.demos.web.utils.MD5Util;
import com.example.forumsystem.demos.web.utils.StringUtil;
import com.example.forumsystem.demos.web.utils.UUIDUtil;
import io.micrometer.core.lang.NonNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
@Api("用户相关接口")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation("用户注册")
    @RequestMapping("/register")
    public Result register (@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                            @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                            @ApiParam("密码") @RequestParam("password") @NonNull String password,
                            @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        // 校验密码与重复密码是否相同,不相同返回错误信息
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return Result.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 生成用户数据
        UserInfo user = new UserInfo();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        userService.createNormalUser(user);
        // 返回成功
        return Result.success(ResultCode.SUCCESS);
    }

    @ApiOperation("用户登录")
    @RequestMapping("/login")
    public Result login(HttpServletRequest request,
                        @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                        @ApiParam("密码") @RequestParam("password") @NonNull String password){
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.info("用户名密码为空，用户名：" + username, ", 密码：" + password);
            return null;
        }

        UserInfo user = userService.login(username, password);
        if (user == null){
            return null;
        }
        HttpSession session = request.getSession(true);
        session.setAttribute(Constans.USER_SESSION, user);
        return Result.success();
    }

    @ApiOperation("获取用户信息")
    @RequestMapping("/getUserMessage")
    public UserInfo getUserMessage(HttpServletRequest request,
                                   @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id){
        UserInfo user = null;
        if (id == null){
            HttpSession session = request.getSession(false);
            log.info("Session：" + session);
            user = (UserInfo) session.getAttribute(Constans.USER_SESSION);
        }else {
            user = userService.selectById(id);
        }

        return user;
    }

    @ApiOperation("退出登录")
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session == null){
            session.invalidate();
        }

        return "退出成功";
    }

    @ApiOperation("修改基本的个人信息")
    @RequestMapping("/modifyBasin")
    public Result modify (HttpServletRequest request,
                                 @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                 @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark) {

        if (StringUtil.isEmpty(nickname) && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark)) {
            log.warn("参数校验失败, 昵称" + nickname
                    + ", 邮箱：" + email + ", 电话号" + phoneNum + ", 个人简介：" + remark);
            return Result.fail();
        }

        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);

        // 3. 封装对象
        UserInfo updateUser = new UserInfo();
        updateUser.setId(user.getId());
        updateUser.setNickname(nickname);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        userService.modifyBasin(updateUser);
        //把更新后的user设置到Session中
        user = userService.selectById(user.getId());
        session.setAttribute(Constans.USER_SESSION, user);

        return Result.success(user);
    }

    @ApiOperation("修改密码")
    @RequestMapping("/modifyPassword")
    public void modifyPassword (HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        if (!newPassword.equals(passwordRepeat)) {
            log.info("确认密码和新密码不一致, 需要重新输入");
        }

        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);

        userService.modifyPassword(user.getId(), newPassword, oldPassword);

        // 销毁session, 强制让用户使用新密码重新登录
        if (session != null) {
            session.invalidate();
        }
    }

}
